package com.nursinghome.user.controller;

import com.nursinghome.admin.service.ElderlyService;
import com.nursinghome.bean.Elderly;
import com.nursinghome.bean.RespBean;
import com.nursinghome.group.ElderlyUpdateGroup;
import com.nursinghome.user.service.UserElderlyService;
import com.nursinghome.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user/elderly")
public class UserInfoController {
    @Autowired
    private UserElderlyService userElderlyService;
    @Autowired
    private ElderlyService elderlyService;

    @GetMapping("/info")
    public RespBean selectInfoByEid(@RequestHeader(value = "token", required = false) String token) {
        //判断令牌
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer eidInt = (Integer) map.get("eid");
        Long  eid = new Long(eidInt + "");
        if (eid == null) {
            return RespBean.error("令牌信息不正确");
        }
        Elderly elderly = userElderlyService.selectInfoByEid(eid);
        return RespBean.ok("",elderly);
    }

    @PutMapping
    public RespBean updateInfo(@RequestBody @Validated({ElderlyUpdateGroup.class})Elderly elderly,
                               @RequestHeader(value = "token", required = false) String token) {
        //判断令牌
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer eidInt = (Integer) map.get("eid");
        Long  eid = new Long(eidInt + "");
        if (eid == null) {
            return RespBean.error("令牌信息不正确");
        }
        elderly.setEid(eid);
        if (!userElderlyService.updateInfo(elderly)) {
            return RespBean.error("修改失败");
        }
        return RespBean.ok("修改成功");
    }
}
